<template>
  <div>
    <div class="draggable-container form-body" :key="element.metaRefresh">
      <a-form
        ref="formRef"
        :model="lowCode.model"
        class="demo-dynamic"
        :layout="element.componentProps.labelPosition"
        :size="element.componentProps.size"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <template v-if="lowCode.isDesigner">
          <draggable
            class="drawing-board grid-layout"
            :style="{
              gridTemplateColumns: `repeat(auto-fill, minmax(${columnWidth}%, 1fr))`,
            }"
            v-model="element.items"
            @add="handleAdd($event)"
            v-bind="{ group: 'group', animation: 200 }"
            tag="div"
            item-key="key"
            handle=".mover"
            :component-data="{ name: 'fade' }"
            :disabled="
              lowCode.disabled && element?.nestedChain?.indexOf('dialog') == -1
            "
          >
            <template #item="{ element: el, index }">
              <div class="grid-item">
                <renderParse
                  :element="el"
                  :key="el.key"
                  :index="index"
                  :parent="element"
                >
                  <template
                    v-for="(_, name) in $slots"
                    :key="name"
                    #[name]="data"
                  >
                    <slot :name="name" v-bind="data" />
                  </template>
                </renderParse>
              </div>
            </template>
          </draggable>
        </template>

        <div
          v-else
          class="drawing-board grid-layout"
          :style="{
            gridTemplateColumns: `repeat(auto-fill, minmax(${columnWidth}%, 1fr))`,
          }"
        >
          <template tag="div" v-for="(el, index) in element.items" :key="index">
            <div v-if="element.key" class="grid-item">
              <render-parse
                :element="el"
                :key="el.key"
                :index="index"
                :parent="element.items"
              >
                <template
                  v-for="(_, name) in $slots"
                  :key="name"
                  #[name]="data"
                >
                  <slot :name="name" v-bind="data" />
                </template>
              </render-parse>
            </div>
          </template>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, inject, toRefs, ref, computed } from "vue";
import type {
  LowCodeImp,
  Component,
  ComponentImp,
} from "@/components/low-code/core/";
import { tools } from "@/components/low-code/page-designer/utils";
import clone from "clone";
import { useComponentPretreatment } from "@/components/low-code/page-designer/hooks";

export default defineComponent({
  name: "formWidget",
  props: ["element"],
  setup(props) {
    const getLowCodeInstance = inject("getLowCodeInstance") as Function;
    const lowCode = getLowCodeInstance() as LowCodeImp;
    const { element } = toRefs<{ element: Component }>(props);
    const component = lowCode.dataCenter[element.value.key] as ComponentImp;

    const formRef = ref(null);
    lowCode.formController.setFormRefs(element.value.selector, formRef);

    const columnWidth = computed(() => {
      return (
        Math.floor(100 / element.value.componentProps.gridTemplateColumns) - 1
      ); // 向下取整
    });

    (<{ ref: any }>element.value.componentProps).ref = formRef;
    const handleAdd = (event: { newIndex: number }) => {
      let hasKey = false;
      const newIndex = event.newIndex;
      if (element.value.items[newIndex]) {
        /****
         * 组件预处理
         */
        if (useComponentPretreatment(lowCode, element.value, newIndex))
          return false;
        hasKey = element.value.items[newIndex].key ? true : false;
        let cacheObject = component.addItem(
          element.value.items[newIndex]
        ) as Component;
        cacheObject.nestedChain = element.value.nestedChain + "_form";
        element.value.items[newIndex] = cacheObject;
        lowCode.setcurrentKey(cacheObject.key);
      }
      hasKey && element.value.updateMetaRefresh();
      tools.handleStack.push(clone(lowCode));
    };

    return {
      lowCode,
      formRef,
      element,
      handleAdd,
      columnWidth,
    };
  },
});
</script>

<style scoped>
.drawing-board {
  min-height: 80px;
}
.grid-layout {
  display: grid;
  grid-template-columns: repeat(
    auto-fill,
    minmax(100%, 1fr)
  ); /* 自动适应两列 */
  gap: 5px; /* 控件之间的间距 */
}

.grid-item {
  width: 100%;
}
</style>
